package com.example.orderfood2.viewAllInformation;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.orderfood2.DatabaseManager.DatabaseManager;
import com.example.orderfood2.R;
import com.example.orderfood2.RecyclerViewAdapter.ClassAdapter;
import com.example.orderfood2.RecyclerViewAdapter.StudentAdapter;
import com.example.orderfood2.Repository.StudentRepository;
import com.example.orderfood2.util.DBUtil;

public class ViewAllStudentInformationActivity extends AppCompatActivity implements StudentAdapter.OnItemClickListener{
    private StudentRepository dbUtil;
    Cursor cursor;
    private RecyclerView recyclerStudentView;
    private StudentAdapter adapter;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        dbUtil= DatabaseManager.getInstance(this).getStudentRepository();
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_view_all_student_information);
        //        创建数据库
//        dbUtil = new DBUtil(this);
        // 初始化RecyclerView
        recyclerStudentView = findViewById(R.id.recyclerStudentView);
        //      作用是确定 RecyclerView 中各个列表项的排列方式为以线性列表的形式展示数据
        recyclerStudentView.setLayoutManager(new LinearLayoutManager(this));
        // 加载数据
        loadClassData();
    }
    private void loadClassData() {
        cursor = dbUtil.getAllStudents();
        adapter = new StudentAdapter(cursor);
        adapter.setOnItemClickListener(this); // 设置按钮点击监听器
        recyclerStudentView.setAdapter(adapter);
    }
    @Override
    public void onEditClick(int position, int id, String username) {
        Intent intent = new Intent(this, EditStudentActivity.class); // 跳转到编辑页面
        intent.putExtra("id", id);
        intent.putExtra("source","ViewAllStudentInformationActivity");
        startActivity(intent);
    }

    @Override
    public void onDeleteClick(int position, int id) {
        new AlertDialog.Builder(this)
                .setTitle("确认删除")
                .setMessage("确定删除此同学吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    dbUtil.deleteStudent(id); // 从数据库删除
                    loadClassData(); // 刷新列表
                })
                .setNegativeButton("取消", null)
                .show();
    }
    @Override
    protected void onDestroy() {
        if (cursor != null) {
            cursor.close();
        }
        dbUtil.close();
        super.onDestroy();
    }
}